﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using System.Threading;

namespace Dtf.Core.Controls
{
    public class MenuItem : UIItem
    {
        public MenuItem(UIItem uiItem)
            : base(uiItem)
        {
        }
     

        public void Expand()
        {
            Thread.Sleep(1000);
            Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, base.Element, TreeScope.Descendants, _menuOpenedHandler = new AutomationEventHandler(OnMenuOpened));
            
            ExpandCollapsePattern expandCollapse = base.Element.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
            
            base.BringToFront();
            Thread.Sleep(1000);
            expandCollapse.Expand();
            _waitEvent.WaitOne();
            Console.Write("Wait Finished");
        }

        public void Collapse()
        {
            ExpandCollapsePattern expandCollapse = base.Element.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
            expandCollapse.Collapse();
        }

        /// <summary>
        /// Use Expand method to open submenu.
        /// </summary>
        public void Invoke()
        {
            
            InvokePattern invoke = base.Element.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
            invoke.Invoke();
            
            
        }

        private void OnMenuOpened(object sender, AutomationEventArgs args)
        {
            LogManager.Write("SubMenuOpened");
            
          //  Automation.RemoveAutomationEventHandler(AutomationElement.MenuOpenedEvent, base.Element, _menuOpenedHandler);
            _waitEvent.Set();
            
        }

        private AutomationEventHandler _menuOpenedHandler;
        private EventWaitHandle _waitEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
        
    }
}
